//
//  GameViewController.m
//  Palabris
//
//  Created by vedat on 23.12.12.
//  Copyright (c) 2012 vedat. All rights reserved.
//

#import "GameViewController.h"
#import "GameoverViewController.h"
#import "RootViewController.h"
# import "SqliteHelper.h"
#import "Fragment.h"
#import <QuartzCore/QuartzCore.h>


@implementation GameViewController
@synthesize goGameOver;
@synthesize goMainMenu;
@synthesize missedWordsTableView;
@synthesize showOrHidenMissedWords;
@synthesize viewMissedWord;
@synthesize gameCharContainer;
@synthesize gameMovableCahr;
@synthesize gamePoint;
@synthesize gameOverButton;

SqliteHelper *sqlHelper;
NSMutableArray *filternArray;
NSTimer *gameTimer;
NSString *gameCharsForRandom=@"ABCDEFGHIJKLMNOÖPRSßRUÜVYZ";
NSString *gameAnimationRight=@"RIGHT";
NSString *gameAnimationLeft=@"LEFT";
float gameTimerInterval=0.05;
int timerValue=0;
int gameCharContainerDefaulOrigin_X=50;
CGRect gameCharContainerDefaultPosition;
CGRect gameCharDefaultPosition;
int charAnimationHeight=12;
int charAnimationDifferenceForOrigin_Y=12;
int maxMissedWordList=40;
CGRect screenBound ;
CGSize screenSize ;
CGFloat screenWidth;
CGFloat screenHeight;
float gameAlphaAnimationValue=0.0;
float charVerticaleAnimationDuration=0.50;
float charHorizontalAnimationDuration=0.40;
bool isAnimationActive=NO;
bool isGameActive=NO;
bool isWordsListShow=NO;
NSString *gameFrakmentKey=@"";
#pragma mark - View lifecycle

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        filternArray=[[NSMutableArray alloc]init];
    }
    return self;
}
// Begin mein Teil

- (void)viewDidLoad
{
    
    [super viewDidLoad];
    sqlHelper= [[SqliteHelper alloc] init];
    
    [sqlHelper removeAll];
    int tableRowCount=sqlHelper.getRowCount;
    if(tableRowCount<=0){
        [sqlHelper readWordsAndInsertTable3:@"woerterbuch" fileType:@"txt"];
    }
    //[sqlHelper printAllTable];
    [sqlHelper removeAllDataWithLength:1];
    //NSLog(@"gefunden: %i",[sqlHelper isKeyContainer:@"a"]);
    //NSLog(@"gefunden: %i",[sqlHelper getRowCount]);
    
    [gameCharContainer setText:@""];
    [gameMovableCahr setText:@""];
    screenBound = [[UIScreen mainScreen] bounds];
    screenSize = screenBound.size;
    screenWidth = screenSize.width;
    screenHeight = screenSize.height;
    gameCharContainerDefaultPosition=CGRectMake(
                                                self.gameCharContainer.frame.origin.x,
                                                gameCharContainerDefaulOrigin_X,
                                                self.gameCharContainer.frame.size.width,
                                                self.gameCharContainer.frame.size.height);
    
    gameCharContainer.frame=gameCharContainerDefaultPosition;
    gameCharDefaultPosition=CGRectMake(((screenWidth/2)-(self.gameMovableCahr.frame.size.width/2)),
                                       screenHeight-50,
                                       self.gameMovableCahr.frame.size.width,
                                       self.gameMovableCahr.frame.size.height);
    
    
    [self.missedWordsTableView.layer setCornerRadius:10.0];
    [self.missedWordsTableView.layer setBorderWidth:1.0];
    [self hiddenTableViewVerticaleAnimation];
    [self hiddenGameButtons];
    
    [self startGameTimer];
	// Do any additional setup after loading the view, typically from a nib.
}

//-(void)

-(void) setGameDafault{
    [self.gameMovableCahr setHidden:NO];
    [self.gamePoint setText:@"0"];
    [self.gameCharContainer setText:@""];
}

- (void)startGameTimer {
    isGameActive=YES;
    if (self.gameCharContainer.text.length == 0) {
        int filterCount=0;
        do {
            gameFrakmentKey=[self generateRandomCharacter];
            filterCount=[sqlHelper getKeyCount:gameFrakmentKey];
        } while (filterCount<=0);
        NSLog(@"geneiert: %@",gameFrakmentKey);
    }
    else{
        filternArray=[sqlHelper findKey:[gameCharContainer text]];
        int filterCount=filternArray.count;
        NSLog(@"Anzahl der gefundenen Woerter: %i",filterCount);
        if (filterCount>0) {
            int randomValue=[self generateNumber:filterCount];
            NSString *randomWord=[filternArray objectAtIndex:randomValue];
            NSLog(@"Random word: %@",randomWord);
            NSLog(@"Frakment word: %@",self.gameCharContainer.text);
            gameFrakmentKey=[self generateRandomCharacterFromString:randomWord key:self.gameCharContainer.text];
            NSLog(@"geneiert: %@",gameFrakmentKey);
        }
    }
    
    [self.gameMovableCahr setText:gameFrakmentKey];
    
	gameTimer=[NSTimer scheduledTimerWithTimeInterval:0.25
                                               target:self selector:@selector(onGameTimer)
                                             userInfo:nil repeats:YES];
}




-(void) onGameTimer {
    timerValue++;
    if (timerValue%2 ==0) {
        self.gameMovableCahr.frame=CGRectMake(gameMovableCahr.frame.origin.x,
                                              gameMovableCahr.frame.origin.y-charAnimationDifferenceForOrigin_Y,
                                              gameMovableCahr.frame.size.width,
                                              gameMovableCahr.frame.size.height+charAnimationHeight);
        
    }
    else{
        self.gameMovableCahr.frame=CGRectMake(self.gameMovableCahr.frame.origin.x,
                                              gameMovableCahr.frame.origin.y-charAnimationDifferenceForOrigin_Y,
                                              gameMovableCahr.frame.size.width,
                                              gameMovableCahr.frame.size.height-charAnimationHeight);
    }
    
	if (self.gameMovableCahr.center.y<gameCharContainerDefaulOrigin_X+
        gameCharContainerDefaultPosition.size.height/2) {
        [gameTimer invalidate];
        [self.gameCharContainer setText:[[self.gameCharContainer text] stringByAppendingString:[self.gameMovableCahr text]]];
        [self setGameCharToStartPosition];
        BOOL result;
        result=[self checkGameOver];
        //[self startGameTimer];
    }
    
}

-(NSString*)generateRandomCharacterFromString:(NSString*)str key:(NSString*)key{
    str=str.uppercaseString;
    key=key.uppercaseString;
    //NSLog(@"word:%@, key:%@",str,key);
    NSUInteger count = 0, length = [str length];
    NSRange range = NSMakeRange(0, length);
    NSRange first;
    NSMutableArray *positions=[[NSMutableArray alloc]init];
    NSString *result=NULL;
    while(range.location != NSNotFound)
    {
        Fragment *frak=[[Fragment alloc] init];
        range = [str rangeOfString: key options:0 range:range];
        first=range;
        if(range.location != NSNotFound)
        {
            range = NSMakeRange(range.location + range.length, length - (range.location + range.length));
            NSLog(@"position:(%i,%i)",first.location, range.location);
            if (first.location==0 && range.location!=str.length) {
                [frak setRight:[str substringWithRange:NSMakeRange(range.location, 1)]];
                NSLog(@"%i--left %@ right %@",count,[frak left],[frak right]);
            }else if (first.location >0 && range.location!= str.length){
                [frak setLeft:[str substringWithRange:NSMakeRange(first.location-1, 1)]];
                [frak setRight:[str substringWithRange:NSMakeRange(range.location, 1)]];
                NSLog(@"%i--left %@ right %@",count,[frak left],[frak right]);
            }
            else if (first.location >0 && range.location== str.length){
                [frak setLeft:[str substringWithRange:NSMakeRange(first.location-1, 1)]];
                //[frak setRight:[tempStr substringWithRange:NSMakeRange(rang.location+rang.length, 1)]];
                NSLog(@"%i--left %@ right %@",count,[frak left],[frak right]);
            }
            [positions addObject:frak];
            count++;
        }
        //[frak release];
        frak=nil;
    }
    
    NSLog(@"Anzahl der Position-en:%i",count);
    if (positions.count>0) {
        int randomPosition=[self generateNumber:positions.count];
        NSLog(@"Generierte Position:%i",randomPosition+1);
        Fragment *fr=[positions objectAtIndex:randomPosition];
        positions=nil;
        //NSLog(@"retain:%i",positions.retainCount);
        //NSLog(@"retain:%i",fr.retainCount);
        if (fr.left==NULL) {
            result=fr.right;
            fr=nil;
            return result;
        } else if (fr.right==NULL) {
            result=fr.left;
            fr=nil;
            return result;
        }
        else //if (fr.left!=NULL &&  fr.right!=NULL)
        {
            int charRandom=[self generateNumber:2];
            if (charRandom==0) {
                result=fr.left;
                fr=nil;
                return result;
            }
            else{
                result=fr.right;
                fr=nil;
                return result;
            }
            
        }
    }
    else
        
        return result;
}



- (int) generateNumber:(int)val{
    srandomdev();
    int randomValue = random()%val;
    return randomValue;
}


- (int) getFac:(int)value{
    if (value == 0) {
        return 1;
    } else {
        return value * [self getFac:(value - 1)];
    }
}


- (int) calcGamePoint:(NSString*) strForCalc{
    return [self getFac:strForCalc.length];
}

- (void) updateGamePoint:(int) value {
    NSLog(@"Update Point:%i",[self getGamePointInt]);
    NSLog(@"Update Point:%i",value);
    
    [self.gamePoint setText:[NSString stringWithFormat:@"%i",(value+[self getGamePointInt])]];
    //[self.gamePoint setText:[NSString stringWithFormat:@"%i",value]];
}


- (NSString*) getGamePointStr{
    return [self.gamePoint text];
}

- (int) getGamePointInt{
    return self.gamePoint.text.intValue;
}

- (void) forthGame{
    [self.gameMovableCahr setText:[self generateRandomCharacter]];
    [self setGameCharToStartPosition];
    [self startGameTimer];
}

- (void) forthGameWithNewWord{
    isGameActive=NO;
    [self.gameMovableCahr setHidden:NO];
    [self.gameCharContainer setText:@""];
    [self.gameOverButton setHidden:YES ];
    [self startGameTimer];
    
}

- (void) callGameOver{
    isGameActive=NO;
    [self setGameCharToStartPosition];
    [self.gameMovableCahr setHidden:YES];
    [self showGameButtons];
}

-(void)showGameButtons{
    [self.gameOverButton setHidden:NO];
    [self.missedWordsTableView setHidden:NO];
    [self.showOrHidenMissedWords setHidden:NO];
    [self.goGameOver setHidden:NO];
    [self.goMainMenu setHidden:NO];
    
    
}

-(void)hiddenGameButtons{
    [self.gameOverButton setHidden:YES];
    [self.missedWordsTableView setHidden:YES];
    [self.showOrHidenMissedWords setHidden:YES];
    [self.goGameOver setHidden:YES];
    [self.goMainMenu setHidden:YES];
    [self hiddenTableViewVerticaleAnimation];
}

- (BOOL) checkGameOver{
    NSString *currentValue=self.gameCharContainer.text;
    //if ([currentValue length]>3) {
    BOOL isContainer=[sqlHelper isKeyContainer:currentValue];
    int count=0;
    if (isContainer) {
        NSLog(@"Wort gefunden!");
        [self updateGamePoint:[self calcGamePoint:currentValue]];
        [self forthGameWithNewWord];
        return YES;
        
    } else {
        count=[sqlHelper getKeyCount:currentValue];
        if(count>0){
            NSLog(@"forthGame");
            [self forthGame];
            return YES;
        }
        else{
            // nicht Weiter laufen existiert keine Wörter, gameover
            NSLog(@"gameOver");
            [self callGameOver];
        }
        return NO;
    }
    
    /*}
     else{
     [self forthGame];
     return NO;
     }
     */
    return NO;
    
    
}

- (void)animationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(SEL)aSelector {
    //NSLog(@"%@",animationID);
    if (finished) {
        isAnimationActive=NO;
        gameMovableCahr.alpha = 1;
        if (animationID==gameAnimationRight) {
            [self.gameCharContainer setText:[[self.gameCharContainer text] stringByAppendingString:[self.gameMovableCahr text]]];
        } else {
            [self.gameCharContainer setText:[[self.gameMovableCahr text] stringByAppendingString:[self.gameCharContainer text]]];
        }
        [self setGameCharToStartPosition];
        [self checkGameOver];
    }
}


-(void) applyVerticaleAnimation:(CGPoint) touchLocation{
    [gameTimer invalidate];
    isAnimationActive=YES;
    [UILabel animateWithDuration:charVerticaleAnimationDuration
                           delay: 0.0
                         options: UIViewAnimationOptionCurveEaseIn
                      animations:^{
                          self.gameMovableCahr.center=CGPointMake(160,70);
                      }
                      completion:^(BOOL finished){
                          [self applyHorizontaleAnimation:touchLocation];
                      }];
}


-(void) applyHorizontaleAnimation:(CGPoint) touchLocation{
    CGPoint endPoint;
    if (touchLocation.x<=screenWidth/2) {
        [UILabel beginAnimations:gameAnimationLeft context:nil];
        endPoint=CGPointMake(0,70);
    } else {
        [UILabel beginAnimations:gameAnimationRight context:nil];
        endPoint=CGPointMake(280,70);
    }
    
    //[gameTimer invalidate];
    isAnimationActive=YES;
    [UILabel setAnimationDelegate:self];
    [UILabel setAnimationDuration:charHorizontalAnimationDuration];
    [UILabel setAnimationRepeatCount:1];
    [UILabel setAnimationCurve:UIViewAnimationCurveEaseOut];
    self.gameMovableCahr.alpha = gameAlphaAnimationValue;
    self.gameMovableCahr.center=endPoint;
    [UILabel commitAnimations];
    
}

-(void) setGameCharToStartPosition{
    timerValue=0;
    self.gameMovableCahr.frame = gameCharDefaultPosition;
}



-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    UITouch * touch=[[event allTouches] anyObject];
    CGPoint location=[touch locationInView:touch.view];
    
    if (isAnimationActive==NO && isGameActive==YES) {
        [self applyVerticaleAnimation:location];
    }
    //NSLog(@" x= %f   y= %f", screenWidth, screenHeight);
    
    /*
     if (CGRectContainsPoint([gameMovableCahr frame],location))
     {
     //self.gameMovableCahr.center=location;
     }
     */
}

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    /*
     UITouch * touch=[[event allTouches] anyObject];
     CGPoint location=[touch locationInView:touch.view];
     if (CGRectContainsPoint([gameMovableCahr frame],location))
     {
     self.gameMovableCahr.center=location;
     }
     */
}

-(void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
    
}


-(NSString*) generateRandomCharacter{
    srandomdev();
    int charPos = random()%[gameCharsForRandom length];
    NSLog(@"%d",charPos);
    return [gameCharsForRandom substringWithRange:NSMakeRange(charPos, 1)];
    //return [[[NSString alloc] initWithCharacters:charss length:2] autorelease];
    
}

- (void)viewDidUnload
{
    [self setGameCharContainer:nil];
    [self setGameOverButton:nil];
    [self setGameMovableCahr:nil];
    [self setGamePoint:nil];
    sqlHelper=nil;
    [self setGameCharContainer:nil];
    [self setGameMovableCahr:nil];
    [self setGamePoint:nil];
    [self setGameOverButton:nil];
    [self setMissedWordsTableView:nil];
    [self setShowOrHidenMissedWords:nil];
    [self setViewMissedWord:nil];
    [self setGoGameOver:nil];
    [self setGoMainMenu:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return NO;
    //return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

- (IBAction)gameOverButton:(id)sender{
    NSLog(@"gameOverButton");
    [self setGameDafault];
    [self hiddenGameButtons];
    [self startGameTimer];
    
}

- (IBAction)showOrHidenMissedWords:(id)sender {
    //if (self.missedWordsTableView.frame.size.height!=0) {
    if(isWordsListShow){
        [self hiddenTableViewVerticaleAnimation];
        //[sender setTitle:@"SHOW MISSED WORDS" forState:UIControlStateNormal];
    }
    else{
        
        [self showTableViewVerticaleAnimation];
        //[sender setTitle:@"HIDDEN MISSED WORDS" forState:UIControlStateNormal];
    }
    
    //[self applyTableViewVerticaleAnimation];
    missedWordsTableView.reloadData;
    
}







- (void)dealloc
{
    
    [gameCharContainer release];
    [gameMovableCahr release];
    [gamePoint release];
    [gameOverButton release];
    
    [missedWordsTableView release];
    [showOrHidenMissedWords release];
    [viewMissedWord release];
    [goGameOver release];
    [goMainMenu release];
    [super dealloc];
    
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}



/*  Push to GameoverViewController
 */
- (IBAction)goGameOver:(id)sender {
    // Als erstes erstellt man ein Object vom ViewController (Page) zu der man hin will
    GameoverViewController *view = [[GameoverViewController alloc] initWithNibName:@"GameoverViewController" bundle:nil];
    
    // Hier bestimmt ich welche Animation der Übergang bekommt
    view.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    
    // Hier ruft man von der NavigationController (der oberste Vater-Controller) die Push Methode, die dich zu anderen View bringt.
    [self.navigationController pushViewController:view animated:YES];
    
    // Das lernen wir später, ist aber auch nötig
    [view release];
}

/*  PopToRoot to RootViewController
 */
- (IBAction)goMainMenu:(id)sender {
    [self.navigationController popToRootViewControllerAnimated:YES];
}





- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    //return filternArray.count;
    return filternArray.count>maxMissedWordList?maxMissedWordList:filternArray.count;
    
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section

{
    return @"";
}

-(NSString*) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section{
    return @"";
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    cell.textLabel.font = [UIFont fontWithName:@"Helvetica" size:15];
    cell.textLabel.text = [filternArray objectAtIndex:indexPath.row];
    return cell;
}




-(void) hiddenTableViewVerticaleAnimation{
    if (self.missedWordsTableView.frame.size.height!=0) {
        [UITableView animateWithDuration:0.32
                                   delay: 0.0
                                 options: UIViewAnimationOptionCurveEaseIn
                              animations:^{
                                  self.missedWordsTableView.frame=CGRectMake(self.missedWordsTableView.frame.origin.x,
                                                                             missedWordsTableView.frame.origin.y,
                                                                             missedWordsTableView.frame.size.width,
                                                                             0);
                              }
                              completion:^(BOOL finished){
                                  isWordsListShow=NO;
                                  [showOrHidenMissedWords setTitle:@"SHOW MISSED WORDS" forState:UIControlStateNormal];
                              }];
    }
}

-(void) showTableViewVerticaleAnimation{
    [UITableView animateWithDuration:0.32
                               delay: 0.0
                             options: UIViewAnimationOptionCurveEaseIn
                          animations:^{
                              self.missedWordsTableView.frame=CGRectMake(self.missedWordsTableView.frame.origin.x,
                                                                         missedWordsTableView.frame.origin.y,
                                                                         missedWordsTableView.frame.size.width,
                                                                         150);
                          }
                          completion:^(BOOL finished){
                              isWordsListShow=YES;
                              [showOrHidenMissedWords setTitle:@"HIDDEN MISSED WORDS" forState:UIControlStateNormal];
                          }];
    
}


@end
